package com.bolt.common.utils;

import com.bolt.common.collection.MapUtil;
import com.bolt.common.reflect.ObjectUtil;
import com.bolt.convention.exception.ServiceException;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2019/6/20.
 */
public class ApacheRequestUtil {

    private static int connectionRequestTimeout = 3000;
    private static int connectionTimeout = 5000;
    private static int soTimeout = 5000;
    private static int idleConnTimeout = 60000;
    private static int checkWaitTime = 60000;
    private static int maxConnPerHost = 10;
    private static int maxTotalConn = 50;

    private static CloseableHttpClient closeableHttpClient;

    static {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();

        @SuppressWarnings("resource")
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        connectionManager.setMaxTotal(maxTotalConn);
        connectionManager.setDefaultMaxPerRoute(maxConnPerHost);
        connectionManager.setDefaultSocketConfig(
                SocketConfig.copy(SocketConfig.DEFAULT)
                        .setSoTimeout(soTimeout)
                        .build()
        );

        IdleConnectionMonitorThread idleConnectionMonitorThread = new IdleConnectionMonitorThread(
                connectionManager, idleConnTimeout, checkWaitTime);
        idleConnectionMonitorThread.setDaemon(true);
        idleConnectionMonitorThread.start();

        HttpClientBuilder httpClientBuilder = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setConnectionManagerShared(true)
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setSocketTimeout(soTimeout)
                        .setConnectTimeout(connectionTimeout)
                        .setConnectionRequestTimeout(connectionRequestTimeout)
                        .build()
                ).setRetryHandler(new HttpRequestRetryHandler() {
                    @Override
                    public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                        return false;
                    }
                });

        closeableHttpClient = httpClientBuilder.build();


    }


    public static String post(String uri, Header header, String postEntity) {
        HttpPost httpPost = new HttpPost(uri);
        if(ObjectUtil.isNotNull(header)){
            httpPost.addHeader(header);
        }
        if (postEntity != null) {
            StringEntity entity = new StringEntity(postEntity, Consts.UTF_8);
            entity.setContentType("application/json;charset=UTF-8");
            httpPost.setEntity(entity);

        }

        try (CloseableHttpResponse response = closeableHttpClient.execute(httpPost)) {
            String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
            return responseContent;
        } catch (Exception ex) {
            throw new ServiceException(ex);
        } finally {
            httpPost.releaseConnection();
        }

    }

    public static String get(String uri, Header header, String queryParam) {
        if (queryParam != null) {
            if (uri.indexOf('?') == -1) {
                uri += '?';
            }
            uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
        }
        HttpGet httpGet = new HttpGet(uri);
        if(ObjectUtil.isNotNull(header)){
            httpGet.addHeader(header);
        }
        try (CloseableHttpResponse response = closeableHttpClient.execute(httpGet)) {
            String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
            return responseContent;
        } catch (Exception ex) {
            throw new ServiceException(ex);
        } finally {
            httpGet.releaseConnection();
        }
    }

    public static String get(String uri, Header header, Map<String, Object> param) {
        HttpGet httpGet = null;
        try {
            URIBuilder builder = new URIBuilder(uri);
            if (MapUtil.isNotEmpty(param)) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, String.valueOf(param.get(key)));
                }
            }
            httpGet = new HttpGet(builder.build());
            if(ObjectUtil.isNotNull(header)){
                httpGet.addHeader(header);
            }
            CloseableHttpResponse response = closeableHttpClient.execute(httpGet);
            String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
            return responseContent;
        } catch (Exception ex) {
            throw new ServiceException(ex);
        } finally {
            if (httpGet != null) {
                httpGet.releaseConnection();
            }
        }
    }

    public static String post(String uri, Header header, Map<String, Object> param) {
        HttpPost httpPost = new HttpPost(uri);
        if(ObjectUtil.isNotNull(header)){
            httpPost.addHeader(header);
        }
        if (MapUtil.isNotEmpty(param)) {
            List<NameValuePair> paramList = new ArrayList<>();
            for (String key : param.keySet()) {
                paramList.add(new BasicNameValuePair(key, String.valueOf(param.get(key))));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
            httpPost.setEntity(entity);
        }
        try {
            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
            String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
            return responseContent;
        } catch (Exception ex) {
            throw new ServiceException(ex);
        } finally {
            httpPost.releaseConnection();
        }
    }


    static class IdleConnectionMonitorThread extends Thread {
        private final HttpClientConnectionManager connMgr;
        private final int idleConnTimeout;
        private final int checkWaitTime;
        private volatile boolean shutdown;

        IdleConnectionMonitorThread(HttpClientConnectionManager connMgr, int idleConnTimeout, int checkWaitTime) {
            super("IdleConnectionMonitorThread");
            this.connMgr = connMgr;
            this.idleConnTimeout = idleConnTimeout;
            this.checkWaitTime = checkWaitTime;
        }

        @Override
        public void run() {
            try {
                while (!this.shutdown) {
                    synchronized (this) {
                        wait(this.checkWaitTime);
                        this.connMgr.closeExpiredConnections();
                        this.connMgr.closeIdleConnections(this.idleConnTimeout,
                                TimeUnit.MILLISECONDS);
                    }
                }
            } catch (InterruptedException ignore) {
            }
        }

        public void trigger() {
            synchronized (this) {
                notifyAll();
            }
        }

        public void shutdown() {
            this.shutdown = true;
            synchronized (this) {
                notifyAll();
            }
        }
    }

}

 